package net.ojbk.saishi.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.Part;

import net.ojbk.saishi.po.syMatch;
import net.ojbk.saishi.service.ContestantService;
import net.ojbk.saishi.service.MatchBackService;
import net.ojbk.saishi.util.StringTool;
import net.ojbk.util.FileTool;
import net.ojbk.util.WebPathTool;

/**
 * 参加赛事 请求的 Servlet
 * Servlet implementation class PartMatchServlet
 */
@WebServlet("/PartMatchServlet")
@MultipartConfig(
        maxFileSize = 100*1024*1024,
        maxRequestSize = 130*1024*1024
)  
public class PartMatchServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public PartMatchServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		response.getWriter().append("Served at: ").append(request.getContextPath());
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// 天才第一步，判断有登录
		request.setCharacterEncoding("UTF-8");
		response.setContentType("text/html; charset=UTF-8");
		PrintWriter out = response.getWriter();
		HttpSession session=request.getSession();
		if (!(session != null && session.getAttribute("login") != null && (boolean)session.getAttribute("login"))) { // 如果未登录
			String message = "<a href=\"./"
					+ FileTool.getFileName(request.getHeader("Referer"))
					+ "\">&nbsp;&nbsp;&nbsp;Return</a>";
			out.write("not login. <br/>" + message);
			System.out.println(FileTool.getFileName(request.getHeader("Referer")));
			return ;
		}
		// 获取 用户ID  获取用户信息
	    String userId = (String)session.getAttribute("myId");
	    // 获取 赛事ID
	    String matchId = request.getParameter("matchId");
	    System.out.println(matchId);
	    

        // 构造 service 层参数
	    // 获取 用户键入 的信息
	    String[] extraInfoName = ContestantService.getExtraInfoName(matchId);
	    String[] extraInfo = new String[extraInfoName.length];
	    for (int i=0; i<extraInfoName.length; i++) {
	    	extraInfo[i] = request.getParameter(extraInfoName[i]);
	    }
	    ContestantService.partMatch(userId, matchId, extraInfo);
	    // TODO 为判断是否已参赛
	    // 对提交上来的赛事文件进行储存
	    syMatch match = MatchBackService.getMatch(matchId);
	    if (match.getNeedFile()) {
	    	String uploadPath = WebPathTool.getMatchDataPath() + userId + File.separator + matchId + File.separator + "treasury" + File.separator;
	 	    File uploadPathFile = new File(uploadPath);
	 	    if (!uploadPathFile.exists()) { // 不存在
	 	    	uploadPathFile.mkdirs();
	 	    }
			System.out.println("uploadPath : " + uploadPath);
			String[] basicInfoName = ContestantService.getBasicInfoName(matchId);
			String[] basicInfo = ContestantService.getBasicInfo(userId, matchId);
			Part part1 = request.getPart("file");
			//TODO
			String formatfileName = StringTool.formatFileName(match.getFileFormat(), basicInfoName, basicInfo, extraInfoName, extraInfo);
			System.out.println("formatfileName\n" + formatfileName);
			File file1 = new File(uploadPath + formatfileName + FileTool.getFileType(part1.getSubmittedFileName()));
			System.out.println("fileName : " + file1.getName() + " \nfilePath : " + file1.getPath());
			part1.write(file1.getPath());
	    }
		response.setStatus(HttpServletResponse.SC_MOVED_TEMPORARILY);
		response.setHeader("Location", "./Statistics.jsp?matchId=" + matchId);
	}

}
